<template>
  <div class="map-container">
    <div id="map" ref="mapContainer"></div>
    <div class="controls">
      <div class="time-filter">
        <label for="startTime">开始时间:</label>
        <input type="datetime-local" v-model="startTime">
        <label for="endTime">结束时间:</label>
        <input type="datetime-local" v-model="endTime">
        <button @click="queryData">查询</button>
      </div>
      
      <div class="playback-controls">
        <button @click="startPlayback" :disabled="isPlaying">播放</button>
        <button @click="pausePlayback" :disabled="!isPlaying">暂停</button>
        <button @click="stopPlayback">停止</button>
        <input type="range" v-model="playbackSpeed" min="1" max="10">
        <label>速度: {{ playbackSpeed }}</label>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import { io } from 'socket.io-client';
import { useMapStore } from '@/stores/map';
import { loadAMapScript } from '@/utils/map-loader';

const mapStore = useMapStore();
const mapContainer = ref(null);
const startTime = ref('');
const endTime = ref('');
const playbackSpeed = ref(5);
const isPlaying = ref(false);

let map = null;
let socket = null;
let currentMarker = null;
let pathLine = null;
let playbackTimer = null;

// 初始化地图
async function initMap() {
  try {
    await loadAMapScript();
    map = new AMap.Map(mapContainer.value, {
      zoom: 11,
      center: [116.397428, 39.90923]
    });
    mapStore.setMap(map);
  } catch (error) {
    console.error('地图初始化失败:', error);
  }
}

// 初始化 WebSocket 连接
function initSocket() {
  socket = io(import.meta.env.VITE_WS_URL);
  
  socket.on('newLocation', (data) => {
    mapStore.addLocationData(data);
    updateMapDisplay(data);
  });
  
  return () => socket.disconnect();
}

// 查询历史数据
async function queryData() {
  if (!startTime.value || !endTime.value) {
    alert('请选择时间范围');
    return;
  }
  
  try {
    const response = await axios.get('/api/locations', {
      params: {
        startTime: startTime.value,
        endTime: endTime.value
      }
    });
    
    mapStore.setLocationData(response.data);
    displayPath();
  } catch (error) {
    console.error('查询数据失败:', error);
  }
}

// 开始回放
function startPlayback() {
  if (!mapStore.locationData.length) return;
  
  isPlaying.value = true;
  const interval = 1000 / playbackSpeed.value;
  
  playbackTimer = setInterval(() => {
    mapStore.updatePlaybackIndex();
    if (mapStore.currentIndex >= mapStore.locationData.length) {
      stopPlayback();
    } else {
      updateMapDisplay(mapStore.locationData[mapStore.currentIndex]);
    }
  }, interval);
}

// 暂停回放
function pausePlayback() {
  isPlaying.value = false;
  if (playbackTimer) {
    clearInterval(playbackTimer);
  }
}

// 停止回放
function stopPlayback() {
  pausePlayback();
  mapStore.resetPlayback();
  if (currentMarker) {
    currentMarker.setPosition([
      mapStore.locationData[0].longitude,
      mapStore.locationData[0].latitude
    ]);
  }
}

onMounted(() => {
  initMap();
  const cleanup = initSocket();
  onUnmounted(() => {
    cleanup();
    if (playbackTimer) {
      clearInterval(playbackTimer);
    }
  });
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

#map {
  width: 100%;
  height: 100%;
}

.controls {
  position: absolute;
  top: 20px;
  left: 20px;
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.time-filter, .playback-controls {
  margin-bottom: 10px;
}

input, button {
  margin: 0 5px;
}
</style> 